//
//  PCMyMessageDetailsViewController.m
//  fruitsDealers
//
//  Created by sgone on 16/3/23.
//  Copyright © 2016年 com.sgone. All rights reserved.
//

#import "PCMyMessageDetailsViewController.h"
#import "PCMyMessageDetailsTableViewCell.h"
#import "IQKeyboardManager.h"
#import "DXMessageToolBar.h"
//#import "PCHttpService.h"
#import "AFNetworking.h"
//#import "HPHttpService.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#import "OMOrderEmptyTableViewCell.h"

@interface PCMyMessageDetailsViewController () <UITableViewDelegate, UITableViewDataSource,UIGestureRecognizerDelegate,DXMessageToolBarDelegate> {
    
    CGFloat cellHeight;
    IQKeyboardManager *manager;
//    PCHttpService *service;
    int currentPage;
    int sizeCount;
    CGFloat emptyCellHeight;
}


@property (strong, nonatomic) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) PCMyMessageDetailsTableViewCell *cell;
@property (strong, nonatomic) DXMessageToolBar *chatToolBar;
@property (nonatomic, strong) OMOrderEmptyTableViewCell *emptyCell;
@property(nonatomic,strong) AFHTTPSessionManager *manager2;


@end

@implementation PCMyMessageDetailsViewController

- (NSMutableArray *)dataArray {
    
    if (_dataArray == nil) {
        
        _dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataArray;
}

//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager2
{
    if (_manager2 == nil) {
        _manager2  = [AFHTTPSessionManager manager];
    }
    return _manager2;
    
    
}



- (DXMessageToolBar *)chatToolBar
{
    if (_chatToolBar == nil) {
        
        _chatToolBar = [[DXMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - [DXMessageToolBar defaultHeight], self.view.frame.size.width, [DXMessageToolBar defaultHeight])];
        _chatToolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _chatToolBar.delegate = self;
        _chatToolBar.maxLength = 350;
    }
    
    return _chatToolBar;
}

- (void)viewDidLoad {
    
 
    
    [super viewDidLoad];
    
    self.titleLabel.text = @"消息回复";
    //    self.isBackBut = YES;
    self.backBtn.hidden = NO;
   
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ViewWidth, ViewHeight - 64 - self.chatToolBar.height) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = FDBack_COLOR;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    manager = [IQKeyboardManager sharedManager];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidKeyBoardClick)];
    tapGesture.numberOfTouchesRequired = 1;
    tapGesture.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tapGesture];
    
    [self.view addSubview:self.chatToolBar];
    
    [self.chatToolBar.inputTextView becomeFirstResponder];
    
//    service = [[PCHttpService alloc] init];
    
//    [self setupDownRefresh];
//    [self setupUpRefresh];
    
    
    
    [self creatData];
    }


-(void)creatData
{
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing13)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在帮你刷新中";
    
    
   

    
    
}



-(void)headerRereshing
{

    sizeCount = 20;
    currentPage = 1;
    [self getInquiryMessageDetailsByService:currentPage size:sizeCount];

}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    manager.enable = NO;
//    manager.shouldResignOnTouchOutside = YES;
//    manager.shouldToolbarUsesTextFieldTintColor = YES;
//    manager.enableAutoToolbar = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    manager.enable = YES;
}

- (void)getInquiryMessageDetailsByService:(int)page size:(int)size {
    
//    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@chart_log_view",SERVER_ADDRESS3];
    NSDictionary *parmas = @{@"cur_page"  : [NSString stringWithFormat:@"%d",page] , @"size" : [NSString stringWithFormat:@"%d",size] ,@"uid" : [self.dataHandler.userDic objectForKey:@"wId"] ,  @"chart_id" : self.chart_id , @"user_type" : @"3" , @"chart_type" : @"2"};
    
    [self.manager2 POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            [self.tableView headerEndRefreshing];
            NSArray *array = responseObject[@"data"][@"list"][@"data"];
            

            
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:array];
            [self.tableView reloadData];
            
        }
        else
        {
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            [self.tableView headerEndRefreshing];
            
            NSString *str = responseObject[@"result_msg"];
            [self.view makeToast:str];
            
            
        }

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
       
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.tableView headerEndRefreshing];
        
        [self.view makeToast:@"请检查网络"];

        
    }];
    
    
   
    
    
    
    
    /*
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [service getInquiryDetailsByPage:[NSString stringWithFormat:@"%d",page] size:[NSString stringWithFormat:@"%d",size] chart_id:self.chart_id uid:self.p_uid user_type:self.p_user_type success:^(NSArray *resultArray) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:resultArray];
                [self.tableView reloadData];
            });
        } error:^(NSString *errorInfo) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideAllHUDsForView:self.tableView animated:YES];
                [OtherLogin otherUserLoginTheSameUsername:errorInfo navigationController:self.navigationController];
            });
        }];
    });
     
     
     */
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.dataArray.count == 0) {
        
        return 1;
    }
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.dataArray.count == 0) {
        
        self.emptyCell = [OMOrderEmptyTableViewCell cellWithTableView:self.tableView];
        self.emptyCell.selectionStyle = UITableViewCellSelectionStyleNone;
        emptyCellHeight = [self.emptyCell setEmptyOrderCell];
        return self.emptyCell;
    }
    self.cell = [PCMyMessageDetailsTableViewCell cellWithTableView:tableView];
    self.cell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.cell.messageDic = self.dataArray[indexPath.row];
    self.cell.row = indexPath.row;
    self.cell.array = self.dataArray;
    cellHeight = [self.cell getCellHeight];
    
    return self.cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.dataArray.count == 0) {
        
        return emptyCellHeight;
        
    }
    return cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

- (void)hidKeyBoardClick {
    
    [self.view endEditing:YES];
}

- (void)sendMessageClick:(NSString *)text {
    
//    NSString *pid = [self.dataArray firstObject][@"pid"];
//    NSString *nums = [self.dataArray firstObject][@"nums"];
//    NSString *p_uid = [self.dataArray firstObject][@"p_uid"];
//    NSString *p_user_type = [self.dataArray firstObject][@"p_user_type"];
//       NSString *parent_id = [self.dataArray firstObject][@"parent_id"];
    
    
//    
//    NSLog(@"qqqqqqqqqq %@    ",self.dict);
//    
//    
//    return;
    __weak PCMyMessageDetailsViewController *weakSelf = self;
    
    
    NSString *pid = [NSString stringWithFormat:@"%@",self.dict[@"pid"]];
    NSString *uid = [NSString stringWithFormat:@"%@",self.dict[@"uid"]];
    NSString *nums = [NSString stringWithFormat:@"%@",self.dict[@"nums"]];
    NSString *user_type = [NSString stringWithFormat:@"%@",self.dict[@"user_type"]];
    NSString *parent_id = [NSString stringWithFormat:@"%@",self.dict[@"id"]];
    
    
    
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@add_chart_log",SERVER_ADDRESS3];
    NSDictionary *parmas = @{@"pid"  : pid , @"uid" : uid, @"nums" : nums , @"user_type" : user_type, @"chart_text" : text, @"chart_type" : @"2", @"parent_id" : parent_id};
    [self.manager2 POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
             [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            
           
            [self headerRereshing];
            
            
            
        }
        
        else
        {
        
            
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];

            
            NSString *str = responseObject[@"result_msg"];
            [self.view makeToast:str];
            
            
        
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
       
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.view makeToast:@"请检查网络"];
        
    }];
    

    
    
    
    /*
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [service setInquiryMessageByPid:pid nums:nums chart_text:text uid:p_uid user_type:p_user_type success:^(NSString *resultStr) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if ([resultStr isEqualToString:@"success"]) {
                    
                    [MBProgressHUD hideAllHUDsForView:weakSelf.tableView animated:YES];
                    
                    [MBProgressHUD showSuccess:@"发送成功"];
                    
                    [weakSelf loadNewShare];
                }
            });
        } error:^(NSString *errorInfo) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideAllHUDsForView:weakSelf.tableView animated:YES];
                [OtherLogin otherUserLoginTheSameUsername:errorInfo navigationController:weakSelf.navigationController];
            });
        }];
    });
     
     */
    [self.view endEditing:YES];
}

#pragma mark - DXMessageToolBarDelegate
- (void)inputTextViewWillBeginEditing:(XHMessageTextView *)messageInputTextView{
    
}

- (void)didSendText:(NSString *)text
{
    if (text && text.length > 0) {
        [self sendMessageClick:text];
    }
}

- (void)scrollViewToBottom:(BOOL)animated
{
    if (self.tableView.contentSize.height > self.tableView.frame.size.height) {
        
        CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
        [self.tableView setContentOffset:offset animated:animated];
    }
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//#pragma mark 进行刷新
//
///**
// *
// *  @brief  集成下拉刷新
// */
//- (void)setupDownRefresh
//{
//    //1.添加刷新控件
//    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
//    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewShare)];
//    //2.进入刷新状态
//    //        [self.tableView.header beginRefreshing];
//}
//
///**
// *
// *  @brief  集成上拉刷新
// */
//- (void)setupUpRefresh
//{
//    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreShare)];
//}
//
///**
// *
// *  @brief  加载更多
// */
//- (void)loadNewShare
//{
//    
//    currentPage = 1;
//    [self getInquiryMessageDetailsByService:currentPage size:sizeCount];
//    
//    //    // 刷新表格
//    [self.tableView reloadData];
//    
//    // 结束刷新
//    [self.tableView.header endRefreshing];
//    
//    //重置加载更多
//    [self.tableView.footer resetNoMoreData];
//    
//}
//
//
///**
// *
// *  @brief  加载更多
// */
//- (void)loadMoreShare
//{
//    currentPage++;
//    
//    /*
//    [service getInquiryDetailsByPage:[NSString stringWithFormat:@"%d",currentPage] size:[NSString stringWithFormat:@"%d",sizeCount] chart_id:self.chart_id uid:self.p_uid user_type:self.p_user_type success:^(NSArray *resultArray) {
//        
//        if (resultArray.count == 0) {
//            //没有更多的数据加载
//            [self.tableView.footer noticeNoMoreData];
//        } else {
//            
//            [self.dataArray addObjectsFromArray:resultArray];
//            [self.tableView reloadData];
//            [self.tableView.footer endRefreshing];
//        }
//    } error:^(NSString *errorInfo) {
//        
//        [OtherLogin otherUserLoginTheSameUsername:errorInfo navigationController:self.navigationController];
//    }];
//    
//    [self.tableView.footer noticeNoMoreData];
//     */
//}


-(void)footerRereshing13
{

    currentPage++;
    sizeCount = 20;
    NSString *urlStr = [NSString stringWithFormat:@"%@chart_log_view",SERVER_ADDRESS3];
    NSDictionary *parmas = @{@"cur_page"  : [NSString stringWithFormat:@"%d",currentPage] , @"size" : [NSString stringWithFormat:@"%d",sizeCount] ,@"uid" : [self.dataHandler.userDic objectForKey:@"wId"] , @"chart_id" : self.chart_id , @"user_type" : @"3" , @"chart_type" : @"2"};
    
    [self.manager2 POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            NSArray *array = responseObject[@"data"][@"list"][@"data"];
            
            
            
            
            if (array.count == 0) {
                
                self.tableView.footerReleaseToRefreshText = @"暂无更多数据";
                self.tableView.footerRefreshingText = @"暂无更多数据";
            }
            else
            {
                
                [_dataArray addObjectsFromArray:array];
                
            }
            
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
            
            
        }
        else
        {
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            [self.tableView footerEndRefreshing];
            
            NSString *str = responseObject[@"result_msg"];
            [self.view makeToast:str];
            
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.tableView headerEndRefreshing];
        
        [self.view makeToast:@"请检查网络"];
        
        
    }];


}

@end
